package cn.com.xy.sms.sdk.service.domainservice;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.DomainDBManager;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.util.BaseRunnable;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.ThreadPoolManager;
import cn.com.xy.sms.util.SdkCallBack;


/**
 * Created by kangwenbo on 2017/3/2.
 */

public class DomainUpdateWhiteList extends BaseRunnable {
    private final String TAG = "DomainUpdateWhiteList";
    private final String REQUEST_URL_DOMIN_GET_WHITE_LIST = "domainData";
    private final String DOMIN_LAST_TIME = "domain_request_last_time";

    private final int TYPE_SINGLE = 1;  //请求单个数据
    private final int TYPE_MULTIPLE = 2;    //请求多个数据
    private int mRequestType;
    private SdkCallBack mSdkCallBack;
    private String mSingleCompanyNum;

    public void requestUpdate() {
        ThreadPoolManager.UPDATE_SERVICE.execute(this);
        mRequestType = TYPE_MULTIPLE;
    }

    public void requestUpdateData(String companyNum, SdkCallBack callBack) {
        mRequestType = TYPE_SINGLE;
        mSdkCallBack = callBack;
        mSingleCompanyNum = companyNum;
        ThreadPoolManager.UPDATE_SERVICE.execute(this);
    }

    @Override
    protected boolean inQueryInterval() {
        if (mRequestType == TYPE_SINGLE) {
            return false;
        }

        long lastTime = SysParamEntityManager.getLongParam(DOMIN_LAST_TIME, 0, Constant.getContext());
        long cycleTime = DexUtil
                .getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_DOMAIN_WHITE_LIST_CYCLE, Constant.DAY);
        if (lastTime + cycleTime < System.currentTimeMillis() && NetUtil.checkAccessNetWork(2)) {
            return false;
        }
        return true;
    }

    @Override
    public void execute() {
        Map<String, String> map = null;
        if (mRequestType == TYPE_SINGLE) {
            //查询单个
            map = new HashMap<String, String>();
            map.put(mSingleCompanyNum, "0");
        } else {
            //查询多个
            map = DomainDBManager.getInstance().queryAllCompanyNumInfo();
        }
        String requestContent = createReqeustContent(map);
        if (StringUtils.isNull(requestContent)) {
            LogManager.e(TAG, "requestContent is null");
        } else {
            sendRequest(requestContent);
        }
    }

    private void sendRequest(String requestContent) {
        NetUtil.executeServiceHttpRequest(REQUEST_URL_DOMIN_GET_WHITE_LIST, requestContent, null, new XyCallBack() {
            @Override
            public void execute(Object... objects) {
                try {
                    JSONObject jb = isValidOfData(objects);
                    SysParamEntityManager.setParam(DOMIN_LAST_TIME, String.valueOf(System.currentTimeMillis()));
                    if (jb == null) {
                        return;
                    } else {
                        analysisData(jb);
                    }
                } catch (Throwable t) {
                    LogManager.e(TAG, "execute", t);
                }
            }
        });
    }

    public void analysisData(JSONObject jsonObject) {
        if (jsonObject.has("pubRespDtoList")) {
            JSONArray jsonArray = jsonObject.optJSONArray("pubRespDtoList");
            List<DomainWhiteBean> list = new ArrayList<DomainWhiteBean>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jb = jsonArray.optJSONObject(i);
                DomainWhiteBean domainWhiteBean = new DomainWhiteBean();
                domainWhiteBean.setDomainName(jb.optString("data"));
                domainWhiteBean.setVersion(jb.optString("version"));
                domainWhiteBean.setPubId(jb.optString("pubId"));
                list.add(domainWhiteBean);
            }
            if (mSdkCallBack != null && list.size() > 0) {
                mSdkCallBack.execute(list.get(0).getDomainName());
            }
            DomainDBManager.getInstance().updateData(list);
        }
    }

    public String createReqeustContent(Map<String, String> queryMap) {
        if (queryMap != null && !queryMap.isEmpty()) {
            try {
                List<String> keys = new ArrayList<String>(queryMap.keySet());
                JSONArray jsonArray = new JSONArray();
                for (String key : keys) {
                    JSONObject ob = new JSONObject();
                    ob.put("pubId", key);
                    ob.put("version", queryMap.get(key));
                    jsonArray.put(ob);
                }
                return jsonArray.toString();
            } catch (Throwable t) {
                LogManager.e(TAG, "createReqeustContent error:", t);
                return null;
            }
        } else {
            return null;
        }
    }

    public JSONObject isValidOfData(Object... objects) throws JSONException {
        if (objects == null || objects.length <= 1) {
            LogManager.e(TAG, "Data error");
            return null;
        }
        LogManager.e("zhao", "req data" + objects[1].toString());
        int flag = (Integer) objects[0];
        if (flag != 3) {
            LogManager.e(TAG, String.valueOf(objects[1]));
            return null;
        }

        String str = objects[1].toString();
        if (!TextUtils.isEmpty(str)) {
            JSONObject jb = new JSONObject(str);
            if (jb.has("code")) {
                if ("90001".equals(jb.optString("code")) || "90004".equals(jb.optString("code"))) {
                    return jb;
                } else {
                    LogManager.e(TAG, str);
                }
            }
        }
        return null;
    }

}